package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.*;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.AuthorService;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    AuthorMapper authorMapper;


    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    UserFeign userFeign;

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    ApCollectionMapper apCollectionMapper;
    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 保存文章信息三张表
     *
     * @param articleDto
     * @return 返回文章的id主键
     */
    @Override
    public ResponseResult savaArticle(ArticleDto articleDto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        //设置作者id
        String authorName = articleDto.getAuthorName();
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getName, authorName));
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者不存在");
        }

        apArticle.setAuthorId(apAuthor.getId().longValue());

        if (apArticle.getId() == null) {//新增
            //补充其他属性
            // 普通文章
            apArticle.setComment(0); //评论
            apArticle.setViews(0);  //阅读
            apArticle.setCollection(0);  //收藏
            apArticle.setLikes(0); //点赞
            //保存article数据到数据库，
            save(apArticle);
            //保存articleConfig数据
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);
            apArticleConfigMapper.insert(apArticleConfig);
            //保存articleContent数据
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        } else {//修改
            //先查后改
            ApArticle article = getById(apArticle.getId());
            if (article==null){
                log.info("ApArticle getById is null: {}", articleDto.getId());
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                        "文章不存在或已下架");
            }
            updateById(apArticle);

            //文章内容修改
            ApArticleContent articleContent = apArticleContentMapper.selectOne( Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId,articleDto.getId() ));
            if (articleContent == null) {
                log.info("articleContent getById is null: {}", articleDto.getId());
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            articleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(articleContent);
        }


        //封装返回主键

        return ResponseResult.okResult(apArticle.getId());
    }


    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        if (dto==null){
             dto = new ArticleHomeDto();
        }
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        Integer size = dto.getSize();
        if (size==null||size>=50){
            size=Math.min(size,50);
        }
        if ( size <= 0) {
            size = 10;
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        List<ApArticle> list = apArticleMapper.loadArticleList(dto, loadtype);

        //处理图片的封面
        ResponseResult result = ResponseResult.okResult(list);
        result.setHost(webSite);


        return result;
    }


    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        if (dto==null||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Long id = dto.getArticleId();
        //查询文章配置信息
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId, id));
        if (apArticleConfig==null || apArticleConfig.getIsDown()
                || apArticleConfig.getIsDelete()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已下架");
        }
        //查询文章详情
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, id));
        if (apArticleContent==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //封装返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("config",apArticleConfig);
        map.put("content",apArticleContent);
        return ResponseResult.okResult(map);
    }


    /**
     * 加载文章详情的初始化配置信息，比如关注、喜欢、不喜欢等
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //参数校验
        if (dto==null||dto.getArticleId()==null||dto.getAuthorId()==null){
            return ResponseResult.okResult(new HashMap<>());
        }
        boolean iscollection=false,isfollow=false;
        //查询是否关注
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.okResult(new HashMap<>());
        }
        ApAuthor apAuthor = authorMapper.selectById(dto.getAuthorId());
        if (apAuthor==null){
            return ResponseResult.okResult(new HashMap<>());
        }
        ApUserFollow userFollow = userFeign.findByUserIdAndFollowId(user.getId(), apAuthor.getUserId());
        if (userFollow!=null){
            isfollow=true;
        }
        //查询是否不喜欢和点赞

        ApArticleRelationDto apDto=new ApArticleRelationDto();
        apDto.setArticleId(dto.getArticleId());
        apDto.setEntryId(user.getId());
        apDto.setType((short) 1);
        Map map = behaviorFeign.findApArticleRelation(apDto);

        //查询是否收藏
        if (map.get("entryId")!=null){
            ApCollection collection = apCollectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery()
                    .eq(ApCollection::getArticleId, dto.getArticleId())
                    .eq(ApCollection::getEntryId, map.get("entryId"))
                    .eq(ApCollection::getType, ApCollection.Type.ARTICLE.getCode()));
            if (collection!=null){
                iscollection=true;
            }
        }

        //封装结果返回
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("iscollection", iscollection);
        /*resultMap.put("islike",map.get("islike"));
        resultMap.put("isunlike",map.get("isunlike"));*/
        resultMap.putAll(map);
        return ResponseResult.okResult(resultMap);
    }
}